﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using XHouse.BusinessLayer;
using XHouse.BusinessLayer.Interface;
using XHouse.MessageQueueEngine.Interfaces;
using XHouse.Model.Message;

namespace XHouse.MessageQueueEngine
{
    /// <summary>
    /// The engine message.
    /// </summary>
    public class EngineMessage : IEngineMessage
    {
        /// <summary>
        /// The _inbox.
        /// </summary>
        private IInbox _inbox;

        /// <summary>
        /// The _outbox.
        /// </summary>
        private IOutbox _outbox;


        private IMessageProcessor _messageProcessor;
        /// <summary>
        /// Initializes a new instance of the <see cref="EngineMessage"/> class.
        /// </summary>
        /// <param name="inbox">
        /// The inbox.
        /// </param>
        /// <param name="outbox">
        /// The outbox.
        /// </param>
        public EngineMessage(IInbox inbox, IOutbox outbox, IMessageProcessor messageProcessor)
        {
            _inbox = inbox;
            _outbox = outbox;

            _inbox.NewMessage += new EventHandler(NewMessageInbox);

            _messageProcessor = messageProcessor;
        }

        /// <summary>
        /// The new message inbox.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void NewMessageInbox(object sender, EventArgs e)
        {
            var message = this._inbox.GetNextMessage();

            var mpThread = new Thread(() => this.MessageProcessing(message));

            mpThread.Start();
        }

        /// <summary>
        /// The message processing.
        /// </summary>
        /// <param name="message18">
        /// The message 18.
        /// </param>
        private void MessageProcessing(Message18 message18)
        {
            //Aca proceso todo y escribo el outbox

            List<Message18> rdo = _messageProcessor.Process(message18);

            foreach (var m18 in rdo)
            {
                _outbox.PutMessage(m18);
            }
            
        }
    }
}
